package com.ttg.common.utils;

import com.ttg.common.config.EncryptsConfig;
import com.ttg.common.exception.BaseException;
import com.ttg.common.utils.sm.GmUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.*;

/**
 * @author huyangzou
 * @create 2020-11-20 10:10
 */
public class BasicUtils {

    private final static String[] HEX_DIGITS = {
            "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"
    };

    /**
     * 拼接key=value&key=value
     */
    public static String sort(TreeMap<String, String> sortedParam) {
        StringBuilder sorted = new StringBuilder();
        for (String key : sortedParam.keySet()) {
            sorted.append(key).append("=");
            if (StringUtils.isEmpty(sortedParam.get(key))) {
                sorted.append("&");
            } else {
                String value = sortedParam.get(key);
                sorted.append(value).append("&");
            }
        }
        String sortedStr = sorted.toString();
        sortedStr = sortedStr.length() - 1 > 0 ? sortedStr.substring(0, sortedStr.length() - 1) : sortedStr;
        return sortedStr;
    }

    /**
     * 拼接key=value&key=value
     */
    public static String sort(Map<String, String> sortedParam, String... values) {
        for (String value : values) {
            sortedParam.remove(value);
        }
        List<String> keys = new ArrayList<>(sortedParam.keySet());
        Collections.sort(keys);
        StringBuilder sorted = new StringBuilder();
        for (String key : keys) {
            sorted.append(key).append("=");
            if (StringUtils.isEmpty(sortedParam.get(key))) {
                sorted.append("&");
            } else {
                String value = sortedParam.get(key);
                sorted.append(value).append("&");
            }
        }
        String sortedStr = sorted.toString();
        sortedStr = sortedStr.substring(0, sortedStr.length() - 1);
        return sortedStr;
    }


    /**
     * 功能描述：自定义map拼接
     */
    public static String sortByDiy(Map<String, String> sortedParam) {
        List<String> keys = new ArrayList<>(sortedParam.keySet());
        Collections.sort(keys);
        StringBuilder sorted = new StringBuilder();
        for (String key : keys) {
            if (sortedParam.get(key) == null || sortedParam.get(key) == "") {
                //sorted.append("&");
            } else {
                sorted.append(key).append("=");
                String value = String.valueOf(sortedParam.get(key));
                sorted.append(value).append("&");
            }
        }
        String sortedStr = sorted.toString();
        sortedStr = sortedStr.substring(0, sortedStr.length() - 1);
        return sortedStr;
    }

    /**
     * byte2hex
     */
    public static String byte2hex(byte[] b) {
        StringBuilder hs = new StringBuilder();
        String stmp = "";
        for (byte value : b) {
            stmp = Integer.toHexString(value & 0xFF);
            if (stmp.length() == 1) {
                hs.append("0").append(stmp);
            } else {
                hs.append(stmp);
            }
        }
        return hs.toString().toUpperCase();
    }

    /**
     * hex2byte
     */
    public static byte[] hex2byte(String strhex) {
        if (strhex == null) {
            return null;
        }
        int l = strhex.length();
        if (l % 2 == 1) {
            return null;
        }
        byte[] b = new byte[l / 2];
        for (int i = 0; i != l / 2; ++i) {
            b[i] = (byte) Integer.parseInt(strhex.substring(i * 2, i * 2 + 2), 16);
        }
        return b;
    }

    /**
     * SHA1
     */
    public static String SHAL1(String decript) {
        try {
            MessageDigest digest = MessageDigest.getInstance(GmUtils.sm4ECBDecrypt(EncryptsConfig.S1));
            digest.update(decript.getBytes(StandardCharsets.UTF_8));
            byte[] messageDigest = digest.digest();
            StringBuilder hexString = new StringBuilder();
            for (byte message : messageDigest) {
                String shaHex = Integer.toHexString(message & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }
            return hexString.toString().toLowerCase();
        } catch (Exception e) {
            throw new BaseException(e.getMessage());
        }
    }

    /**
     * MD5
     */
    public static String MD5(String data) {
        try {
            MessageDigest md = MessageDigest.getInstance(GmUtils.sm4ECBDecrypt(EncryptsConfig.M5));
            return byteArrayToHexString(md.digest(data.getBytes(StandardCharsets.UTF_8))).toLowerCase();
        } catch (Exception e) {
            throw new BaseException(e.getMessage());
        }
    }

    /**
     * byteArrayToHexString
     */
    private static String byteArrayToHexString(byte[] b) {
        StringBuilder resultSb = new StringBuilder();
        for (byte aB : b) {
            resultSb.append(byteToHexString(aB));
        }
        return resultSb.toString();
    }

    /**
     * byteToHexString
     */
    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0) {
            n += 256;
        }
        int d1 = n >>> 4;
        int d2 = n % 16;
        return HEX_DIGITS[d1] + HEX_DIGITS[d2];
    }

    /**
     * 转换成url参数，不忽略为空的值
     *
     * @param requestParam 待转换参数
     * @param coder        编码
     * @return xxx=111&xxx=你好  或者  xxx=111&xxx=%E4%BD%A0%E5%A5%BD
     */
    public static String httpBuildQuery(Map<String, String> requestParam, String coder) {
        if (null == coder || "".equals(coder)) {
            coder = "UTF-8";
        }
        StringBuffer sf = new StringBuffer("");
        String reqstr = "";
        if (null != requestParam && 0 != requestParam.size()) {
            for (Map.Entry<String, String> en : requestParam.entrySet()) {
                try {
                    sf.append(en.getKey()
                            + "="
                            + (null == en.getValue() || "".equals(en.getValue()) ? "" : URLEncoder.encode(en.getValue(), coder))
                            + "&");
                } catch (UnsupportedEncodingException e) {
                    return "";
                }
            }
            if (sf.length() > 0) {
                reqstr = sf.substring(0, sf.length() - 1);
            }
        }
        return reqstr;
    }


}
